<?php
namespace app\admin\controller;
class Group extends Action
{
    public function index()
    {       
        return $this->fetch('index');
    }
    public function lists(){
        $pagesize = input('pagesize');
        $pages = input('pages');
        if($pages<=1)
        $a = 0;
        else
        $a = $pagesize*($pages-1);
        $total = db("group")->alias("a")->count();
        $totalpage = ceil($total/$pagesize);
        $data = db("group")->alias("a")
                ->field('a.id,a.name,a.desc,FROM_UNIXTIME(a.addtime,"%Y年%m月%d日") as addtime')
                ->order("a.addtime","desc")
                ->limit($a,$pagesize)
                ->select();
        return json(['code'=>1,'message'=>"获取数据成功",'data'=>$data,'totalpage'=>$totalpage]);
    }
    public function add(){
        if(request()->isPost()){
            $data= input("post.");
            $data["addtime"] = time();
            $data["rules"]   = json_encode(input('rules/a'));
            $data["menus"]   = json_encode(input('menus/a'));
            $save = db('group')->insert($data);
            if($save){
                return backUrl();
            }
        }
        //读取分类相关信息
        $ruleRes = [];
        $typeDb = db("type");
        $typeRes = model("Type")->getType();
        foreach($typeRes[15] as $k => $v){
            $ruleRes[$k] = $v;
            $ruleRes[$k]["children"] = $typeDb->where("cid","=",$v['id'])->select();
        }
        return $this->fetch('add',['ruleRes'=>$ruleRes]);
    }
    public function edit(){
            $id = input("id");
            if(request()->isPost()){
                $data= input("post.");
                $data["addtime"] = time();
                $data["rules"]   = json_encode(input('rules/a'));
                $data["menus"]   = json_encode(input('menus/a'));
                $update = db('group')->where('id',$id)->update($data);
                if($update!==false){
                   return backUrl();
                }
            }
            $data = db('group')->where('id',$id)->find();
            //读取分类相关信息
            $ruleRes = [];
            $typeDb = db("type");
            $typeRes = model("Type")->getType();
            foreach($typeRes[15] as $k => $v){
                $ruleRes[$k] = $v;
                $ruleRes[$k]["children"] = $typeDb->where("cid","=",$v['id'])->select();
            }
            return $this->fetch('edit',['data'=>$data,'ruleRes'=>$ruleRes]);
    }
    public function delete(){
        $id=input('id');
        //删除用户表
        $dels = db('guanli')->where("ma_l","in",$id)->delete();
        $del = db('group')->where("id","in",$id)->delete();
        if($dels&&$del){
            return 1;
        }else{
            return 0;
        }
    }
}